"use client";
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
  ProTableProps,
} from "@ant-design/pro-components";
import { Button, message, Tag } from "antd";
import { useRef } from "react";
import { getLogininforListApi, clearLogininforApi } from "@/lib/api/system/log";
import { Logininfor } from "@/lib/api/system/log.d";
import { useRequest } from "ahooks";
import { getDictDatasByTypesApi } from "@/lib/api/system/dict";
import { getDictValueEnum } from "@/lib/utils/dict";
import { formatOrderParams } from "@/lib/utils/format";
import { download } from "@/lib/utils/file";

export default function Page() {
  const actionRef = useRef<ActionType>();

  const { data: dictData } = useRequest(() =>
    getDictDatasByTypesApi(["sys_common_status"]),
  );

  const [statusMap] = dictData ?? [[], []];

  const { run: clearRun } = useRequest(clearLogininforApi, {
    manual: true,
    onSuccess: () => {
      setTimeout(() => {
        actionRef.current?.reload();
      }, 500);
    },
  });

  const { loading: exportOperlogLoading, run: exportOperlog } = useRequest(
    () => download("/monitor/logininfor/export", {}, "登录日志.xlsx"),
    {
      manual: true,
      onSuccess: () => {
        message.success("导出成功");
      },
    },
  );

  const colums: ProColumns<Logininfor>[] = [
    {
      title: "访问编号",
      dataIndex: "infoId",
      key: "infoId",
      search: false,
    },
    {
      title: "用户名称",
      dataIndex: "userName",
      width: 120,
      key: "userName",
      sorter: true,
    },
    {
      title: "客户端",
      dataIndex: "clientKey",
      key: "clientKey",
      width: 100,
      search: false,
    },
    {
      title: "设备类型",
      dataIndex: "deviceType",
      key: "deviceType",
      width: 100,
      search: false,
    },
    {
      title: "地址",
      dataIndex: "ipaddr",
      key: "ipaddr",
      ellipsis: true,
      width: 110,
    },
    {
      title: "登录地址",
      dataIndex: "loginLocation",
      key: "loginLocation",
      width: 100,
      search: false,
    },
    {
      title: "操作系统",
      dataIndex: "os",
      key: "os",
      ellipsis: true,
      width: 110,
      search: false,
    },
    {
      title: "浏览器",
      dataIndex: "browser",
      key: "browser",
      width: 100,
      search: false,
    },
    {
      title: "登录状态",
      dataIndex: "status",
      key: "status",
      width: 100,
      valueEnum: getDictValueEnum(statusMap),
      render: (_, record) => {
        return (
          <Tag color={record.status === "0" ? "success" : "error"}>
            {statusMap.find((item) => item.dictValue === `${record.status}`)
              ?.dictLabel ?? "-"}
          </Tag>
        );
      },
    },
    {
      title: "描述",
      dataIndex: "msg",
      key: "msg",
      width: 100,
      search: false,
    },
    {
      title: "访问时间",
      dataIndex: "loginTime",
      key: "loginTime",
      valueType: "dateTime",
      width: 200,
      hideInSearch: true,
      sorter: true,
    },
    {
      title: "访问时间",
      dataIndex: "loginTime",
      valueType: "dateRange",
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            "params[beginTime]": value[0] + " 00:00:00",
            "params[endTime]": value[1] + " 23:59:59",
          };
        },
      },
    },
  ];

  const proTableProps: ProTableProps<Logininfor, any> = {
    columns: colums,
    rowKey: "infoId",
    headerTitle: "登录日志",
    expandable: {
      defaultExpandAllRows: true,
    },
    pagination: {
      pageSize: 10,
    },
    actionRef: actionRef,
    options: {
      fullScreen: true,
    },
    toolBarRender: () => {
      return [
        <Button key="clear" type="primary" onClick={clearRun}>
          清空
        </Button>,
        <Button
          key="export"
          loading={exportOperlogLoading}
          type="primary"
          onClick={exportOperlog}
        >
          导出
        </Button>,
      ];
    },
    request: async (params, sort) => {
      const res = await getLogininforListApi({
        ...params,
        ...formatOrderParams(sort),
      });

      return {
        data: res.rows,
        success: true,
        total: res.total,
      };
    },
    onRequestError(e) {
      message.error(e.message);
    },
  };

  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      <ProTable {...proTableProps}></ProTable>
    </PageContainer>
  );
}
